import {useRequest} from 'umi';
import {useSetState} from 'ahooks';
import {getFilter} from '@/services/global';

export interface tableFilterItem {
    text: string;
    value: number | string;
}

export interface Filters {
    tablefilters: {
        areaList?: tableFilterItem[];
        gradeList?: tableFilterItem[];
        departmentList?: tableFilterItem[];
        subjectList?: tableFilterItem[];
    };
    selectOptions: {
        areaList?: API.CommonFilterItem[];
        gradeList?: API.CommonFilterItem[];
        departmentList?: API.CommonFilterItem[];
        subjectList?: API.CommonFilterItem[];
    };
    filterMaps: {
        areaList?: object;
        gradeList?: object;
        departmentList?: object;
        subjectList?: object;
    }
}

export default function useFilterModel() {
    const [state, setState] = useSetState<Filters>({
        tablefilters: {},
        selectOptions: {},
        filterMaps: {}
    });
    const {data: filters} = useRequest(getFilter, {
        onSuccess(data) {
            const tablefilters = {};
            const selectOptions = {};
            const filterMaps = {};
            Object.keys(data || {}).forEach(key => {
                tablefilters[key] = data[key]?.map(item => ({
                    text: item?.label,
                    value: item?.key,
                })) || [];
                selectOptions[key] = data[key]?.map(item => ({
                    ...(item || {}),
                    value: item?.key
                })) || [];
                // 将后端list数据转换成键值对，方便映射成汉字
                filterMaps[key] = data[key]?.reduce((total, cur) => {
                    total[cur.key] = cur.label;
                    return total;
                }, {});
                setState({
                    tablefilters,
                    selectOptions,
                    filterMaps
                });
            });
        }
    }) || {};
    return {
        filters,
        ...state
    };
}
